const redis = require("redis");

const port = 6379;
const host = "localhost";
const pwd = "";
const db = 12;

const client = redis.createClient(port, host, {
	db,
});

let instance;

client.on("connect", () => {
	instance = client;
});

const obj = {
	getActKey(key) {
		return `act_${key}`;
	},
	setActionLock(key, ttl, val) {
		if (!key) {
			key = 0;
		}
		const cKey = this.getActKey(key);
		return new Promise(async (res, rej) => {
			await client.setnx(cKey, val, async (err, v) => {
				if (err === null) {
					await client.expire(cKey, ttl);
					res(v);
				} else {
					rej(err);
				}
			});
		});
	},
	getActionLock(key) {
		if (!key) {
			key = 0;
		}
		const cKey = this.getActKey(key);
		client.get(cKey, function(err, v) {
			console.log("#######", v);
		});
	},
	rmActionLock(key) {
		const cKey = this.getActKey(key);
		return new Promise(async (res, rej) => {
			await client.del(cKey, async (err, v) => {
				if (err === null) {
					res(v);
				} else {
					rej(err);
				}
			});
		});
	},
};

(async () => {
	try {
		const s = await obj.setActionLock("abc", 15, "hello");
		console.log("!!!", s);
		obj.getActionLock("abc");
	} catch (e) {
		console.log("********", e);
	}
	await obj.rmActionLock("abc");
	obj.getActionLock("abc");
})();